package cn.uncode.springcloud.gateway.ribbon;


import java.util.HashSet;
import java.util.Set;

import org.apache.commons.lang3.StringUtils;

/**
 * Ribbon discovery filter context, stores the attributes based on which the server matching will be performed.
 *
 * @author Juny
 */
public class RibbonContext {
	

	private String canaryFlag;
	
	private Set<String> appNames = new HashSet<>();
	
	public String toString() {
		StringBuffer sb = new StringBuffer();
		sb.append(canaryFlag).append(":");
		for(String item:appNames) {
			sb.append(item).append(",");
		}
		sb.deleteCharAt(sb.lastIndexOf(","));
		return sb.toString();
	}
	
	public void valueOf(String value) {
		if(StringUtils.isNotBlank(value)) {
			String[] arr = value.split(":");
			canaryFlag = arr[0];
			if(StringUtils.isNotBlank(arr[1])) {
				String[] names = arr[1].split(",");
				for(String name:names) {
					if(StringUtils.isNotBlank(name)) {
						appNames.add(name);
					}
				}
			}
		}
	}

	public void setCanaryFlag(String canaryFlag) {
		this.canaryFlag = canaryFlag;
		this.appNames = RibbonContextHolder.getAppNameByFlag(canaryFlag);
	}
	
	public boolean containsCanaryAppName(String appName) {
		return appNames.contains(appName);
	}

	public String getCanaryFlag() {
		return canaryFlag;
	}
	
	
	
}
